package concurrent.synchronized_;

public class SynchronizedTest {

    private static  Object object=new Object();



    /**
     * synchronized修饰代码块
     */
    public void test1() throws InterruptedException {
        synchronized (this) {
            while (true) {
                System.out.printf("线程：%s %n", Thread.currentThread().getName() + "进入了普通代码块");
                Thread.sleep(1000);
            }
        }
    }


    /**
     * synchronized修饰方法
     */
    public synchronized void test2() throws InterruptedException {
        while (true) {
            System.out.printf("线程：%s %n", Thread.currentThread().getName() + "进入了普通方法");
            Thread.sleep(1000);
        }
    }

    /**
     * synchronized修饰静态方法
     */

    public static synchronized void test3() throws InterruptedException {
        while (true) {
            System.out.printf("线程：%s %n", Thread.currentThread().getName() + "进入了静态方法");
            Thread.sleep(1000);
        }
    }

    /**
     * synchronized修饰静态方法块
     */

    public static void test4() throws InterruptedException {
        synchronized (SynchronizedTest.class) {
            while (true) {
                System.out.printf("线程：%s %n", Thread.currentThread().getName() + "进入了静态方法块");
                Thread.sleep(1000);
            }
        }
    }

    /**
     * synchronized对任意属性加锁
     */

    public  void test5() throws InterruptedException {
        String lock = "lock";
        synchronized (object) {
            while (true) {
                System.out.printf("线程：%s %n", Thread.currentThread().getName() + "进入了方法块");
                Thread.sleep(1000);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedTest synchronizedTest = new SynchronizedTest();
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    SynchronizedTest synchronizedTest1 = new SynchronizedTest();
                    synchronizedTest.test2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                try {
                    SynchronizedTest synchronizedTest2 = new SynchronizedTest();
                    synchronizedTest.test5();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread1.start();
        thread2.start();
    }


}
